<template>
  <el-dialog
    v-model="visible"
    title="更新代理商配置"
    width="600px"
    @close="resetForm"
  >
    <el-form
      ref="userFormRef"
      label-position="top"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="代理商名称" prop="brandName">
        <el-input v-model="form.brandName" placeholder="请输入代理商名称" />
      </el-form-item>
      <el-form-item label="支付地址" prop="paymentWalletAddress">
        <el-input
          v-model="form.paymentWalletAddress"
          placeholder="请输入支付地址"
        />
      </el-form-item>
      <el-form-item label="Telegram机器人名称" prop="telegramBotName">
        <el-input
          v-model="form.telegramBotName"
          placeholder="请输入Telegram机器人名称"
        />
      </el-form-item>
      <el-form-item label="Telegram机器人Token" prop="telegramBotToken">
        <el-input
          v-model="form.telegramBotToken"
          placeholder="请输入Telegram机器人Token"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { createUser } from "@/api/userApi";
import { message } from "@/utils/message";

interface UserForm {
  agentId: string;
  brandName: string;
  paymentWalletAddress: string;
  telegramBotName: string;
  telegramBotToken: string;
}

const visible = ref(false);

const form = reactive<UserForm>({
  agentId: "",
  brandName: "",
  paymentWalletAddress: "",
  telegramBotName: "",
  telegramBotToken: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  brandName: [{ required: true, message: "请输入代理商名称", trigger: "blur" }],
  paymentWalletAddress: [
    { required: true, message: "请输入支付地址", trigger: "blur" }
  ],
  telegramBotName: [
    { required: true, message: "请输入Telegram机器人名称", trigger: "blur" }
  ],
  telegramBotToken: [
    { required: true, message: "请输入Telegram机器人Token", trigger: "blur" }
  ]
};

const userFormRef = ref<FormInstance>();

const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        console.log(form);
        // message("创建成功", { type: "success" });
        // visible.value = false;
        // emits("refresh");
      } catch (error) {
        console.error(error);
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};

const open = (data: UserForm) => {
  for (let key in form) {
    form[key] = data[key] ?? "";
  }
  visible.value = true;
};

defineExpose({ open });
</script>
